#!/usr/bin/env ruby
# frozen_string_literal: true

require 'optparse'
require 'tmpdir'
require_relative '../lib/shell'
require_relative '../lib/git'
require_relative '../lib/packages'
require_relative '../lib/dotfiles'

@actions = []
OptionParser.new do |opts|
  opts.banner = '安装和初始化 tmux'

  opts.on('-i', '--install', '执行安装步骤') do
    @actions.push('install')
  end
  opts.on('-c', '--configure', '执行初始化步骤') do
    @actions.push('configure')
  end
end.parse!
@actions = %w[install configure] if @actions.empty?

def install_tmux(version)
  packages.install 'libevent:devel', 'ncurses:devel'

  timestamps = Time.new.to_i
  tar_file = "/tmp/tmux-#{version}-#{timestamps}.tar.gz"
  shell.exec "wget -O #{tar_file} https://github.com/tmux/tmux/releases/download/#{version}/tmux-#{version}.tar.gz"

  workdir = Dir.mktmpdir("tmux-#{version}-")
  shell.exec "tar -xzvf #{tar_file} -C #{workdir}"

  Dir.chdir(File.join(workdir, "tmux-#{version}")) do
    shell.exec './configure'
    shell.exec 'make'
    shell.exec 'sudo make install'
  end
end

def config_tmux
  no_config_doc = <<~END_NO_CONFIG
    没有执行初始化动作，因为没有发现 dotfiles 仓库。请首先克隆 dotfiles 仓库

        git clone #{ENV['GITEE_ORIGIN']}/dotfiles.git ~/.config/dotfiles

    然后重新执行配置

        setup-env tmux -c

  END_NO_CONFIG

  dotfiles.around '~/.config/dotfiles/tmux.conf', '~/.tmux.conf', no_config_doc do
    git.clone_or_skip 'https://github.com/edouard-lopez/tmux-tomorrow.git', '~/.tmux/themes/tomorrow'
    git.clone_or_skip 'https://github.com/tmux-plugins/tpm', '~/.tmux/plugins/tpm'
    puts '打开你的 tmux 终端，然后发送命令 `Prefix + I`，这样即安装了插件。'
  end
end

if @actions.include?('install')
  print '请确认安装的版本（如 `3.3`）：'
  version = gets.strip
  version = '3.3' if version.empty?
  install_tmux(version)
end
config_tmux if @actions.include?('configure')
